let websocket = null;
let onMessageCallback = null;
let keepAliveTimer = null;

let LuaRpc = {};

// 打开 WebSocket 连接
LuaRpc.openWebSocket = function(url, onMessage) {
    onMessageCallback = onMessage;
    
    // 判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket(url);
        
        // 连接发生错误的回调方法
        websocket.onerror = function () {
            onMessageCallback("WebSocket连接发生错误");
        }

        // 连接成功建立的回调方法
        websocket.onopen = function () {
            onMessageCallback("WebSocket连接成功");
            keepAliveTimer = setInterval(keepAlive, 5000);
        }

        // 接收到消息的回调方法
        websocket.onmessage = function (event) {
            onMessageCallback(event.data);
            resetKeepAliveTimer();
        }

        // 连接关闭的回调方法
        websocket.onclose = function () {
            clearInterval(keepAliveTimer);
            onMessageCallback("WebSocket连接关闭");
        }
        
        return websocket;
    }
    else {
        alert('当前浏览器不支持 WebSocket ！')
        return null;
    }    
}

// 关闭WebSocket连接
LuaRpc.closeWebSocket = function() {
    websocket.close();
}

// 发送消息
LuaRpc.send = function(message) {
    websocket.send(message);
    resetKeepAliveTimer();
}

// 保活
function keepAlive() {
    LuaRpc.send("return;");
}

// 重新计时
function resetKeepAliveTimer() {
    clearInterval(keepAliveTimer);
    keepAliveTimer = setInterval(keepAlive, 10000);
}
